#!/usr/bin/env python


import os
import tempfile


from .utils import check_output


class tmux:

    def run_command(self, args):
        return check_output(args)

    def currently_in_a_session(self):
        return os.getenv('TMUX') is not None

    def send_keys(self, pane_id, command):
        self.run_command(['tmux', 'send-keys', '-t', pane_id, command + '\n'])

    def get_base_index(self):
        raw = self.run_command(['tmux', 'show-options', '-g'])
        lines = raw.split('\n')
        for line in lines:
            if line.startswith('base-index '):
                return line.split()[1]
        return 0

    def new_session(self, name, size_x, size_y):
        self.run_command(['tmux', 'new-session', '-d', '-s', name, '-x', size_x, '-y', size_y])

    def new_window(self, name, id):
        self.run_command(['tmux', 'new-window', '-d', '-n', name, '-t', id])

    def rename_window(self, id, name):
        self.run_command(['tmux', 'rename-window', '-t', id, name])

    def move_window(self, from_id, to_id):
        self.run_command(['tmux', 'move-window', '-s', from_id, '-t', to_id])

    def add_pane(self, window_id):
        self.run_command(['tmux', 'split-window', '-d', '-v', '-t', window_id])
        self.run_command(['tmux', 'select-layout', '-t', window_id, 'tiled'])

    def set_layout(self, id, layout):
        self.run_command(['tmux', 'select-layout', '-t', id, layout])

    def list_sessions(self):
        return self.run_command(['tmux', 'list-sessions', '-F', '#{session_name} #{session_width} #{session_height}'])

    def list_windows(self, session):
        return self.run_command(['tmux', 'list-windows', '-t', session, '-F', '#{window_index} #{window_layout} #{window_name}'])

    def list_panes(self, id):
        return self.run_command(['tmux', 'list-panes', '-t', id, '-F', '#{line} #{pane_pid} #{pane_tty}'])

    def get_pane_screenshot(self, pane_id):
        temp_file = tempfile.NamedTemporaryFile(delete=False)
        temp_file.close()
        self.run_command(['tmux', 'capture-pane', '-t', pane_id])
        self.run_command(['tmux', 'save-buffer', '-b', '0', temp_file.name])
        self.run_command(['tmux', 'delete-buffer', '-b', '0'])
        screenshot = open(temp_file.name).read()
        os.remove(temp_file.name)
        return screenshot

    def put_pane_screenshot(self, pane_id, screenshot):
        temp_file = tempfile.NamedTemporaryFile('w', delete=False)
        print >>temp_file, screenshot
        temp_file.close()
        self.send_keys(pane_id, ' cat ' + temp_file.name + ' ; rm -f ' + temp_file.name)
